angular.module('app')

.controller('TaskListController', function($scope,$http,TaskService) {
	
	$scope.paginationConf = {
            currentPage: 1,
            totalItems: 100,
            itemsPerPage: 10,
            pagesLength: 7,
            perPageOptions: [10],
            rememberPerPage: 'perPageItems',
            onChange: function(){
				
            }
        };
	// init tasks
	TaskService.findAllTasks().success( 
		function(data) {
			$scope.tasks = data;
			console.log("get " + data.length + " tasks");
			if (data.length > 0) {
				$scope.selectedTask = data[0];
				$scope.selectedIndex = 0;
				$scope.initSelectedRow();
			}
			$scope.paginationConf.totalItems=$scope.tasks.length;
		}
    );
	
	$scope.initSelectedRow = function() {
		// Frequency
		$scope.frenquencyChanged();
		
		// RunStatus
		var runStatus = $scope.selectedTask.runStatus;
		if (runStatus == 0) {
			$scope.selectedTask.runStatusLabel = "New";
		} else if (runStatus == 1) {
			$scope.selectedTask.runStatusLabel = "Started";
		} else if (runStatus == 2) {
			$scope.selectedTask.runStatusLabel = "Finished";
		} else if (runStatus == 3) {
			$scope.selectedTask.runStatusLabel = "Error";
		} else {
			$scope.selectedTask.runStatusLabel = "New";
		}
		console.log("initSelectedRow: runStatusLabel is " + $scope.selectedTask.runStatusLabel);
	}
	
	$scope.frenquencyChanged = function() {
		$scope.setNextSDateTimeTextInput($scope.selectedTask);
		console.log("frenquencyChanged: nextSDateTimeTextInput is " + $scope.selectedTask.nextSDateTimeTextInput);
		
		// update frequencyLabel
		var frequency = $scope.selectedTask.frequency
		console.log("frenquencyChanged: frequency is " + $scope.selectedTask.frequency);
		if (frequency == 1) {
			$scope.selectedTask.frequencyLabel = "Once"
		} else if (frequency == 2) {
			$scope.selectedTask.frequencyLabel = "Daily"
		} else if (frequency == 3) {
			$scope.selectedTask.frequencyLabel = "Weekly"
		} else if (frequency == 4) {
			$scope.selectedTask.frequencyLabel = "Custom"
			$scope.selectedTask.cronExpression = "0 0 17 * * ?"
		}
		
	}
	
	$scope.setNextSDateTimeTextInput = function(task){
		// var nextSDateTime = new Date(task.nextSDateTimeStr.replace(/-/g,"/"))
		var nextSDateTime = new Date();
		nextSDateTime.setTime(task.nextSDateTime);
		
		console.log("nextSDateTime is " + nextSDateTime);
		var frequency = $scope.selectedTask.frequency;
		// Once
		if (frequency == 1) {
			$scope.selectedTask.nextSDateTimeTextInput = nextSDateTime.format("yyyy-MM-dd hh:mm")
		// Daily/Weekly
		} else if (frequency == 2 || frequency == 3) {
			$scope.selectedTask.nextSDateTimeTextInput = nextSDateTime.format("hh:mm")
		} 
		console.log("setNextSDateTimeTextInput: nextSDateTimeTextInput is " + $scope.selectedTask.nextSDateTimeTextInput);
	}
	
	$scope.$watch('selectedTask.nextSDateTimeTextInput', function(newValue, oldValue) {
		if (newValue === oldValue) { return; }
		var frequency = $scope.selectedTask.frequency;
		// Once
		if (frequency == 1) {
			$scope.selectedTask.nextSDateTimeStr = newValue;
		// Daily/Weekly
		} else if (frequency == 2 || frequency == 3) {
			var newDate = new Date()
			// have passed today's planned time
			if (newDate.format("hh:mm") > newValue) {
				newDate = new Date(newDate.getTime() + 1 * 24 * 60 * 60 * 1000); // date +1
			}
			var newDateTimeStr = newDate.format("yyyy-MM-dd ") + newValue;
			$scope.selectedTask.nextSDateTimeStr = newDateTimeStr;
		} 
		$scope.selectedTask.nextSDateTime = new Date($scope.selectedTask.nextSDateTimeStr.replace(/-/g,"/"));
		console.log("watch: new nextSDateTime is " + $scope.selectedTask.nextSDateTime);
	})
	
	$scope.$watch('selectedTask.cronExpression', function(newValue, oldValue) {
		if (newValue === oldValue) { return; }
		if (newValue == null || newValue == undefined) { return; }

		$http(
			{
				method: 'GET',
				url: 'getNextValidTime.es',
				params: {cronExpression: escape($scope.selectedTask.cronExpression)},
			})
		.success( 
			function(data) {
				$scope.selectedTask.nextSDateTime = data;
				var nextSDateTime = new Date();
				nextSDateTime.setTime(data);
				$scope.selectedTask.nextSDateTimeStr = nextSDateTime.format("yyyy-MM-dd hh:mm");
				$('#warningMsgForTaskDetail').html("");
			}
		)
		.error( 
			function(data) {
				$('#warningMsgForTaskDetail').html("<font color='red'>Invalid cron expression!</font>");
			}
		);
		console.log("watch: new nextSDateTime is " + $scope.selectedTask.nextSDateTime);
	})
	
	// edit/update/cancel/delete
	$scope.edit = function(){
		$scope.showTaskEdit = !$scope.showTaskEdit;
		angular.copy($scope.selectedTask, $scope.master);
		console.log("copying selectedTask to master. new master: " + $scope.master);
	}
	$scope.update = function(){
		// save task
		$scope.showTaskEdit = !$scope.showTaskEdit;
		TaskService.saveOrUpdateTask($scope.selectedTask).success(
			function(data) {
				$scope.selectedTask = data;
			}
		)
	}
	$scope.cancel = function(){
		angular.copy($scope.master, $scope.selectedTask);
		console.log("copying master to selectedTask. new selectedTask: " + $scope.selectedTask);
		
		$scope.setNextSDateTimeTextInput($scope.selectedTask);
		$scope.showTaskEdit = !$scope.showTaskEdit;
	}
	$scope.delete = function(){
		if (!confirm("Do you want to delete it?")) {
			window.event.returnValue = false;
		} else {
			// delete task
			TaskService.deleteTask($scope.selectedTask).success(
				function(data) {
					$scope.tasks.splice($scope.selectedIndex,1);
					if ($scope.selectedIndex == 0) {
						$scope.selectedTask = $scope.tasks[0];
					} else {
						$scope.selectedTask = $scope.tasks[$scope.selectedIndex-1];
					}
				}
			)
		}
	}
	
	$scope.chooseTaskForModal = function(){
		$('#modal-createtask').modal('hide')
		
		var selectedOption;
		for (var index in $scope.taskOptions) {
			var obj = $scope.taskOptions[index]
			if (obj.name == $scope.taskOptions.selectedName) {
				selectedOption = obj;
				break;
			}
		}
		console.log(selectedOption)
		$scope.tasks.splice(0,0, selectedOption);
		$scope.selectedTask = selectedOption;
		$scope.initSelectedRow();
		$scope.showTaskEdit = false;
		$scope.paginationConf.totalItems = $scope.paginationConf.totalItems + 1;
	}
	
	$scope.monitorTaskChg = function(){
		console.log($scope.taskOptions.selectedName)
	}
	
	$scope.selectCurrentTask=function(index) {
    	$scope.selectedTask = $scope.tasks[index];
    	$scope.selectedIndex = index;
    };
    
	
	//////////////////Initialization /////////////////////

	$scope.currentPage = "TaskMgr";
	
	// used for e/u/d stock
    $scope.showTaskEdit = true;
    $scope.master = {};
	
	TaskService.loadTaskDefs().success(
		function(data) {
			$scope.taskOptions = data;
			$scope.taskOptions.selectedName = $scope.taskOptions[0].name;
		}
	)
	
	//////////////////Initialization /////////////////////
	
})
